using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections.ObjectModel;

namespace CLFramework.ScheduledTasks
{
    public sealed class TaskManager
    {
        private static readonly TaskManager taskManager = null;
        private List<TaskThread> taskThreads = new List<TaskThread>();

        static TaskManager()
        {
            taskManager = null;
            taskManager = new TaskManager();
        }

        private TaskManager()
        {
        }

        public static TaskManager Instance()
        {
            taskManager.LoadConfiguration();
            return taskManager;
        }

        public void LoadConfiguration()
        {
            TaskConfiguration config = TaskConfiguration.GetConfig();
            this.taskThreads = config.TaskThreads;
            TaskApplication application = TaskApplication.Instance();
            foreach (ITaskModule module in config.Modules.Values)
            {
                module.Init(application);
            }
            application.Modules = config.Modules;
        }

        public bool IsTaskEnabled(string taskName)
        {
            foreach (TaskThread thread in this.taskThreads)
            {
                if (thread.CurrentTasks.ContainsKey(taskName))
                {
                    return thread.CurrentTasks[taskName].Enabled;
                }
            }

            return false;
        }

        public void Start()
        {
            TaskApplication.Instance().ExecuteTaskStartupEvents();
            foreach (TaskThread thread in this.taskThreads)
            {
                thread.InitializeTimer();
            }
        }

        public void Stop()
        {
            List<TaskThread>.Enumerator enumerator = this.taskThreads.GetEnumerator();
            TaskApplication.Instance().ExecuteTaskStartupEvents();
            foreach (TaskThread thread in this.taskThreads)
            {
                thread.Dispose();
            }
            this.taskThreads.Clear();
            TaskApplication.Instance().ExecuteTaskShutdownEvents();
        }

        public IList<TaskThread> TaskThreads
        {
            get
            {
                return new ReadOnlyCollection<TaskThread>(this.taskThreads);
            }
        }
    }


}
